package cn.tsmchina.one.controller.m;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.pojo.OrderPojo;
import cn.tsmchina.one.service.order.OrderService;
import cn.tsmchina.one.util.JsonUtil;

@Controller
public class CartController
{
	@Autowired
	private OrderService orderService;
	
//	@Autowired
//	private UserService userService;
	
	@RequestMapping("/cart")
	public String cart(HttpServletRequest request)
	{
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			request.setAttribute("credits", user.getCredits());
		} else {
			//未登录，0积分
			request.setAttribute("credits", "<a href='user/login?cid='>请登录后查看积分</a>");
		}
		return "m/cart";
	}
	
	@RequestMapping("/submitOrder")
	@ResponseBody
	public Object submitOrder(String data, long customerId, HttpServletRequest request)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			//由于推荐商品的数据格式不同，故作特殊处理，时间紧急暂时这么处理
			if(data.indexOf("summary") != -1){
				data = data.replaceAll("summary", "price");
			}
			if(data.indexOf("recName") != -1){
				data = data.replaceAll("recName", "name");
			}			
			
			/**/
			OrderPojo order = JsonUtil.parseObject(OrderPojo.class, data);
			if(order==null) {
				//没有登录
				return map;
			}
			order.setCustomerId(customerId);
			map = orderService.addOrder(order);
			//增加积分
			/*User user = (User) request.getSession().getAttribute("user");
			if(user!=null) {
				int newCredits = user.getCredits()+(int)Math.ceil(order.getTotalPrice());
				user.setCredits(newCredits);
				userService.update(user);
			}*/
//			map.put("type", "online");
//			map.put("url", "order/info");
		} catch (Exception e)
		{
			e.printStackTrace();
			map.put("type", "error");
			map.put("msg","出错了!");
		}
		return map;
	}
}
